﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Context;
using CNRegex.Web.Base;
using CNRegex.Dal;
using CNRegex.Web.Utility;
using Project.Common;

namespace CNRegex.Web
{
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801

	public class MvcApplication : System.Web.HttpApplication
	{
		public static void RegisterGlobalFilters(GlobalFilterCollection filters)
		{
			filters.Add(new ElmahHandleErrorAttribute());
		}

		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.RouteExistingFiles = false;
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
			routes.IgnoreRoute("{resource}favicon.ico/{*pathInfo}");
			routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" });

			routes.MapRoute("AccountHomePage", "{name}/{p}/{c}/{t}"
					, new { controller = "AccountHome", action = "Index", p = UrlParameter.Optional, c = UrlParameter.Optional, t = UrlParameter.Optional }
					, new { name = new UserHomeRouteConstraint() });

			routes.MapRoute(
				"Default", // Route name
				"{controller}/{action}/{id}", // URL with parameters
				new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
			);
		}

		protected void Application_Start()
		{
			#region configure nhibernate
			NHibernateHelper.Configure();
			#endregion
			#region configure log4net
			Log4netHelper.Configure();
			#endregion


			AreaRegistration.RegisterAllAreas();
			ControllerBuilder.Current.SetControllerFactory(typeof(BaseControllerFactory));
			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);
			DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
		}

		protected void Application_BeginRequest(object sender, EventArgs e)
		{
			if (WebTools.IsNotExcuteAspx(Context.Request.CurrentExecutionFilePathExtension))
				return;
			var session = NHibernateHelper.SessionFactory.OpenSession();
			CurrentSessionContext.Bind(session);
		}


		protected void Application_EndRequest(object sender, EventArgs e)
		{
			if (WebTools.IsNotExcuteAspx(Context.Request.CurrentExecutionFilePathExtension))
				return;
			var session = CurrentSessionContext.Unbind(NHibernateHelper.SessionFactory);
			session.Dispose();
		}
	}
}